package com.et114.components.xmlparse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.jdom.*;
import org.jdom.output.*;
import org.jdom.input.*;
import org.jdom.output.Format.TextMode ;


import java.io.*;
import java.util.*;

import org.springframework.util.Assert;

import com.et114.core.common.AppContext;

/**
 * @author guanhw
 */
public class JDomUtil {
	private static Log					logger				= LogFactory.getLog( JDomUtil.class );
	public JDomUtil ( ) {
	}

	/**
	 * 
	 * @param fileName
	 * @return
	 * @throws Exception
	 */
	public Document getDocument ( String fileName ) throws Exception {
		Assert.notNull( fileName , "xml文件不能为空！" ) ; 
		Assert.state( fileName.endsWith( ".xml" ) , "文件必须为xml文件！" ) ; 
		SAXBuilder builder = new SAXBuilder();
		File _file = new File( fileName ) ; 
		if ( !_file.exists() ) {
			logger.error( fileName + " 不存在！" );
			throw new Exception( fileName + " 不存在！"  ) ; 
		}
		if ( !_file.canRead() ) {
			logger.error( fileName + "  不能读！" ) ;
			throw new Exception( fileName + " 不能读！"  ) ; 
		}
	
		InputStream	is = new FileInputStream( _file );
		Document doc = builder.build( is );
		is.close();
		return doc;
	}

	/**
	 * 
	 * @param doc
	 * @param path
	 * @return
	 */
	public Element getElement ( Document doc , String path ) {
		Element elm = doc.getRootElement();
		if ( path == null || path.trim().length() == 0 ) return elm;
		StringTokenizer st = new StringTokenizer( path, "/" );
		while ( st.hasMoreTokens() ) {
			String name = st.nextToken();
			Element elm1 = elm.getChild( name );
			if ( elm1 == null ) {
				elm1 = new Element( name );
				elm.addContent( elm1 );
			}
			elm = elm1;
		}
		return elm;
	}
	
	/**
	 * 
	 * @param parent
	 * @param childName
	 * @param attrName
	 * @param value
	 * @return
	 */
	public Element getChildByAttribute ( Element parent , String childName , String attrName , String value ) {
		Element elm = null;
		List list = parent.getChildren( childName );
		for ( int i = 0; i < list.size(); i++ ) {
			Element child = ( Element ) list.get( i );
			String tmp = child.getAttributeValue( attrName );
			if ( value.equals( tmp ) )
				return child;
			child = getChildByAttribute( child, childName, attrName, value );
			if ( child != null )
				return child;
		}
		return elm;
	}	
	
	/**
	 * 
	 * @param doc
	 * @param fileName
	 * @param charSet
	 * @throws Exception
	 */
	public  void write( Document doc , String fileName , String charSet ) throws Exception {
		Assert.notNull( fileName , "xml文件不能为空！" ) ; 
		if ( charSet == null || "".equals( charSet.trim() ) ) charSet = AppContext.getFrameWorkPropertiesBean().getCharSet() ;
		Format format = Format.getPrettyFormat();
		format.setEncoding( charSet ) ;
		format.setTextMode( TextMode.TRIM ) ; 
		XMLOutputter outer = new XMLOutputter( format );
		PrintWriter pw = new PrintWriter( new FileOutputStream( fileName ) );
		outer.output( doc, pw );
		pw.close();
	}	
	
	
	
	public static void main( String[] s ) {
		JDomUtil jdu = new JDomUtil();
		try {
			Document doc = jdu.getDocument( "D:/work/test/reportCenter.xml" ) ; 
			Element e = jdu.getElement( doc , "/users" ) ;
		    logger.info( e.getName() ) ;
		    e = jdu.getChildByAttribute( e , "user", "name", "guanhw" ) ;
		    logger.info( e.getAttribute( "name" ) ) ;
		    
		    jdu.write( doc , "D:/work/test/reportCenter2.xml" , "GBK" ) ;
		} catch ( Exception e ) {
			logger.error( e.getMessage() , e ) ; 
		}
		
	}
}
